<template>
  <div class='container'>
    <div class='userinfo'>
      <img :src="userInfo.avatarUrl"
           alt="头像">
      <p>{{userInfo.nickName}}</p>
    </div>
    <year-progress> </year-progress>
    <button v-if='userInfo.openId'
            @click='scanBook'
            class='btn'>添加图书</button>
    <button v-else
            open-type="getUserInfo"
            lang="zh_CN"
            class='btn'
            @getuserinfo="doLogin">点击登录</button>
  </div>
</template>

<script>
import { post, showSuccess, showModal } from '@/utils'
import config from '@/config'
import qcloud from 'wafer2-client-sdk'
import YearProgress from '@/components/YearProgress'
export default {
  data () {
    return {
      userInfo: {
        avatarUrl: '/static/img/unlogin.png',
        nickName: '暂无昵称'
      }
    }
  },
  mounted () {
    let userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.userInfo = userInfo
    }
  },
  methods: {
    async addBook (isbn) {
      const res = await post('/weapp/addBook', {
        isbn,
        openId: this.userInfo.openId
      })
      console.log(res)
      showModal('添加成功', `${res.title}添加成功`)
    },
    scanBook () {
      wx.scanCode({
        onlyFromCamera: true,
        success: (res) => {
          if (res.result) {
            this.addBook(res.result)
          }
        }
      })
    },
    doLogin () {
      let that = this
      let user = wx.getStorageSync('userInfo')
      if (!user) {
        qcloud.setLoginUrl(config.loginUrl)
        qcloud.login({
          success: function (userInfo) {
            console.log('登录成功', userInfo)
            wx.setStorageSync('userInfo', userInfo)
            showSuccess('登录成功')
            that.userInfo = userInfo
          },
          fail: function (err) {
            console.log('登录失败', err)
          }
        })
      }
    }
  },
  components: {
    YearProgress
  }
}
</script>

<style lang='scss'>
.container {
  padding: 0 30rpx;
}
.userinfo {
  text-align: center;
  margin-top: 100rpx;
  img {
    width: 150rpx;
    height: 150rpx;
    margin: 20rpx;
    border-radius: 50%;
  }
}
</style>
